package datastruct.bst;

/**
 * Description: binary search tree
 * Created By xxm
 */
public class BST<E extends Comparable<E>> {
    // tree node
    private class Node {
        public E e;
        public Node left;
        public Node right;

        public Node(E e) {
            this.e = e;
            this.left = null;
            this.right = null;
        }
    }

    private Node root;
    private int size;

    public BST() {
        root = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Add an element in binary search tree.
     * This method don't deal with same elements.
     *
     * @param e
     */
    public void add(E e) {
        root = add(root, e);
    }

    /**
     * Insert an element in binary search tree base on root recursively.
     * Not visible to users.
     *
     * @param node
     * @param e
     * @return root of tree which has added an element.
     */
    private Node add(Node node, E e) {

        if (node == null) {
            size++;
            return new Node(e);
        }

        if (e.compareTo(node.e) < 0)
            node.left = add(node.left, e);
        else if (e.compareTo(node.e) > 0)
            node.right = add(node.right, e);

        return node;
    }

    /**
     * Search an element in bst.
     *
     * @param e
     * @return
     */
    public boolean contains(E e) {
        return contains(root, e);
    }

    /**
     * Search recursively.
     *
     * @param node
     * @param e
     * @return
     */
    private boolean contains(Node node, E e) {
        if (node == null)
            return false;

        if (e.compareTo(node.e) == 0)
            return true;
        else if (e.compareTo(node.e) > 0)
            return contains(node.right, e);
        else // e.compareTo(node.e) < 0
            return contains(node.left, e);
    }

    public void preOrder() {
        preOrder(root);
    }

    private void preOrder(Node node) {
        if (node == null)
            return;
        System.out.println(node.e);

        preOrder(node.left);
        preOrder(node.right);
    }
}
